import Taro from '@tarojs/taro';
import { sleep } from './timer';

const hideLoading = () => Taro.hideLoading();

const loading = function (title: string) {
  Taro.showLoading({
    title,
  });

  return hideLoading;
};

const success = function (
  title: string,
  duration?: number,
  showIcon?: boolean,
) {
  return new Promise<void>(resolve => {
    Taro.showToast({
      icon: showIcon ?? true ? 'success' : 'none',
      title,
      duration,
      complete: async () => {
        await sleep(duration ?? 0);
        resolve();
      },
    });
  });
};

const error = function (title: string, duration?: number) {
  return new Promise<void>(resolve => {
    Taro.showToast({
      icon: 'none',
      title,
      duration,
      complete: async () => {
        await sleep(duration ?? 0);
        resolve();
      },
    });
  });
};

const message = {
  loading,
  hideLoading,
  success,
  error,
};

export default message;
